const querystring = require('querystring');
const { set, get } = require('./src/db/redis');
const handleBlogRouter = require('./src/router/blog');
const handleUserRouter = require('./src/router/user');
const { access } = require('./src/utils/log');

// const SESSION_DATA = {};
const getPostData = req => {
  const promise = new Promise((resolve, reject) => {
    if(req.method !== 'POST') {
      resolve({})
      return;
    }
    if(req.headers['content-type'] !== 'application/json') {
      resolve({})
      return;
    }
    let payload = '';
    req.on('data', chunk => {
      payload += chunk.toString();
    })
    req.on('end', () => {
      if(!payload) {
        resolve({})
        return;
      }
      resolve(JSON.parse(payload));
    })
  })
  return promise;
}

const getCookieExpires = () => {
  const d = new Date();
  d.setTime(d.getTime() + (24 * 60 * 60 * 1000));
  return d.toGMTString();
}

const serverHandle = function(req, res) {
  access(`${req.headers['user-agent']} —— ${req.method} —— ${req.url}`)
  res.setHeader('Content-type', 'application/json');
  const url = req.url;
  const pathArray = url.split('?');
  const cookieString = req.headers.cookie || '';

  req.cookie = {};
  cookieString.split(';').forEach(item => {
    if(!item) return;
    // item.match(/(\w+)=(\w+)/, (str, key, value) => {
    //   req.cookie[key.trim()] = value.trim();
    // })
    const [key, value] = item.split('=');
    req.cookie[key.trim()] = value.trim();
  })
  let userId = req.cookie.userid;
  let needSetCookie = false;

  req.path = pathArray[0];
  req.query = querystring.parse(pathArray[1]);
  if(!userId) {
    /**
     * 没有userId，说明还没登陆过；
     * 服务端生成userId，并登陆后，存储对应信息；
     * 服务端设置cookie；
     */
    needSetCookie = true;
    userId = `${Date.now()}_${Math.random()}`;
    set(userId, {});
  }
  req.sessionId = userId;
  get(req.sessionId).then(sessionData => {
    if(sessionData == null) {
      set(req.sessionId, {});
      res.session = {};
    }else {
      req.session = sessionData;
    }
    return getPostData(req);
  }).then(payload => {
    req.payload = payload;
    const blogRes = handleBlogRouter(req, res);

    if(blogRes) {
      blogRes.then(list => {
        if(needSetCookie) {
          res.setHeader('Set-Cookie', `userid='${userId}';path=/;expires=${getCookieExpires()};httpOnly;`)
        }
        res.end(JSON.stringify(list))
      })
      return;
    }

    const userRes = handleUserRouter(req, res);
    if(userRes) {
      userRes.then(user => {
        if(needSetCookie){
          res.setHeader('Set-Cookie', `userid='${userId}';path=/;expires=${getCookieExpires()};httpOnly;`)
        }
        res.end(JSON.stringify(user))
      })
      return;
    }

    res.writeHead(404, {"Content-type": "text/plain"})
    res.write("404 NOT FOUND")
    res.end();
  })
}

module.exports = serverHandle;
